<template>
  <div v-if="showChart" ref="chart" style="width: 100%; height: 100%"></div>
  <nodata-box v-else></nodata-box>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'BasicBarChart',
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      },
      required: true
    },
    xAxisData: {
      type: Array,
      default: () => {
        return []
      },
      required: true
    },
    legendsData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null,
      labelWidth: 80
    }
  },
  computed: {
    showChart: function () {
      return this.data[0].length > 0
    },
    series: function () {
      return this.data.map((item, index) => {
        return {
          type: 'bar',
          name: this.legendsData[index] || '',
          data: item,
          barWidth: '24px'
        }
      })
    }
  },
  watch: {
    data() {
      if (this.chart) {
        this.updateChart()
      } else {
        this.$nextTick(() => this.updateChart())
      }
    }
  },
  mounted() {
    this.init()
    // 屏幕缩放的时候，重绘echarts
    window.addEventListener('resize', this.resize, false)
  },
  unmounted() {
    this.destroyChart()
    window.removeEventListener('resize', this.resize, false)
  },
  methods: {
    init() {
      if (this.data.length === 0 || this.data[0].length === 0) {
        return
      }
      const currentOptions = this.buildBarOption()
      if (!this.chart) this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption(currentOptions)
    },
    buildBarOption() {
      return {
        legend: {
          show: this.legendsData.length >= 1,
          right: 16,
          top: 20,
          itemWidth: 0,
          itemHeight: 0,
          formatter: function (name) {
            return '{rect|} ' + name // 使用 rect 标记 + 文本的方式来自定义 icon
          },
          // 自定义图例样式
          textStyle: {
            rich: {
              rect: {
                width: 12,
                height: 12,
                borderRadius: 1,
                backgroundColor: '{color| }'
              }
            }
          }
        },
        color: ['#3366ff'],
        grid: {
          top: this.legendsData.length >= 1 ? 60 : 30,
          right: 16,
          bottom: 16,
          left: 20,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            lineStyle: {
              type: 'solid', // 将虚线改为实线
              width: 32, // 设置背景的宽度
              color: 'rgba(51,102,255,0.1)',
              opacity: 0.8,
              z: -100
            }
          },
          // formatter: function (params) {
          //   const { axisValueLabel, data } = params[0]
          //   const color = data.color
          //   return `<div><div style="border-radius: 2px; background-color: ${color}; padding: 5px;"></div><div>${axisValueLabel}: ${data.value}</div>`
          // },
          formatter: function (params) {
            const { axisValueLabel, data, color } = params[0]
            const { value } = data
            const legendHtml = `<div class="series-item"><div class='marker' style="background-color:${color}"></div><div class="content-container"><div class="content-name">${axisValueLabel}</div><div class="content-value">${value}</div></div></div>`
            return legendHtml
          },
          extraCssText:
            'box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.16);border-radius: 2px;border: 1px solid #D9D9D9;padding: 8px 16px'
        },
        xAxis: {
          type: 'category',
          data: this.xAxisData,
          axisTick: { show: false },
          axisLabel: {
            interval: 0,
            fontSize: 12,
            fontFamily: 'PingFangSC-Regular, PingFang SC',
            fontWeight: 400,
            color: '#8C8C8C',
            width: this.labelWidth,
            overflow: 'truncate'
          }
        },
        yAxis: {
          axisLabel: {
            fontSize: 12,
            fontFamily: 'PingFangSC-Regular, PingFang SC',
            fontWeight: 400,
            color: '#262626',
            margin: 8
          },
          name: '个',
          nameLocation: 'end', // 设置标题位置为中间
          nameGap: 12,
          nameTextStyle: {
            fontSize: 12,
            align: 'right',
            verticalAlign: 'bottom',
            padding: [0, 8, 0, 0],
            color: '#262626'
          }
        },
        series: this.series
      }
    },
    resize() {
      if (this.chart && this.$refs.chart) {
        const width = this.$refs.chart.clientWidth
        const labelWidth = width / 8 - 20
        if (this.labelWidth !== labelWidth) {
          this.labelWidth = labelWidth
          this.updateChart()
        }
        this.chart.resize()
      }
    },
    destroyChart() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    updateChart() {
      this.destroyChart()
      this.init()
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep {
  .marker {
    display: inline-block;
    margin-right: 5px;
    width: 8px;
    height: 8px;
    border-radius: 2px;
    background-color: red;
  }
  .series-item {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .content-container {
      display: flex;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      line-height: 17px;
      width: 80%;
      .content-name {
        color: #5c5c5c;
        font-weight: 400;
        font-size: 12px;
        margin-right: 12px;
      }
      .content-value {
        font-weight: 500;
        color: #262626;
      }
    }
  }
}
</style>
